package com.xiaofei.Filter;

import com.xiaofei.Tools.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
//@WebFilter("/*")
public class LoginFilter implements Filter {
//    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        String url = req.getRequestURI();
        log.info("url为:{}",url);
        //放行
        if (url.contains("login")){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token = req.getHeader("token");
        if (token == null){
            res.setStatus(401);
            return;
//            throw new BusinessException("未登录，请先登录");
        }

        Claims claims = null;
        try {
            claims = JwtUtil.parseClaims(token);
            log.info("claims为:{}",claims);
        } catch (Exception e) {
            res.setStatus(401);
            log.info("token解析失败，请重新登录:{}",e.getMessage());
//            throw new RuntimeException("未登录，请先登录");
            return;
        }
        //放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
